package com.yc.controller;

import com.yc.service.ProductCrawlerService;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 商品爬虫控制器，提供API接口供前端调用
 */
@RestController
@RequestMapping("/api/crawler")
public class ProductCrawlerController {

    private final ProductCrawlerService productCrawlerService;

    public ProductCrawlerController(ProductCrawlerService productCrawlerService) {
        this.productCrawlerService = productCrawlerService;
    }

    /**
     * 通用爬取接口
     *
     * @param supplierName 供应商名称
     * @param supplierUrl  供应商URL
     * @param cookies      可选的Cookie信息
     * @return 爬取结果
     */
    @PostMapping("/crawl")
    public Map<String, Object> crawl(@RequestParam String supplierName,
            @RequestParam String supplierUrl,
            @RequestParam(required = false) String cookies) {

        List<String> logs = new ArrayList<>();
        Map<String, Object> response = new HashMap<>();

        try {
            logs.add("开始爬取商品数据...");
            logs.add("供应商: " + supplierName);
            logs.add("爬取URL: " + supplierUrl);

            // 调用爬取服务
            Map<String, Object> result = productCrawlerService.crawlProducts(supplierUrl, cookies);

            // 构建响应
            response.put("success", true);
            response.put("supplierName", supplierName);
            response.put("products", result.get("products"));
            response.put("logs", result.getOrDefault("logs", logs));
            response.put("cookies", result.get("cookies"));

            logs.add("爬取完成，成功获取 " + ((List<?>) result.get("products")).size() + " 个商品");

        } catch (Exception e) {
            response.put("success", false);
            response.put("error", "爬取失败: " + e.getMessage());
            logs.add("错误: " + e.getMessage());
            e.printStackTrace();
        }

        response.put("logs", logs);
        return response;
    }
}
